package io.jt808.proto;

import io.norland.buffer.AutoBuffer;
import io.norland.proto.IProto;
import lombok.Data;

@Data
public class WrapperHeader implements IProto {

    /**
     * 消息ID，2个字节，无符号16位
     */
    private int messageId;

    /**
     * 消息体长度
     */
    private int messageLength;

    /**
     * 加密方式
     */
    private int encryption;
    /**
     * 消息体属性
     */
    private int messageBodyProperty;

    /**
     * 终端手机号
     */
    private String simId;

    /**
     * 消息流水号
     */
    private int messageSerialNo;

    /**
     * 总包数
     */

    private int messageTotalPacketsCount;

    /**
     * 分包号
     */

    private int messagePacketNo;

    /**
     * 分包发送
     */
    private boolean isPackage;

    public final byte[] writeToBytes() {
        AutoBuffer buff = new AutoBuffer();
        buff.writeShort((short) messageId);
        int messageBodyProperty = 0;
        if (isPackage) {
            messageBodyProperty = 1 << 13;
        }
        messageBodyProperty = messageBodyProperty | (messageLength & 0x03FF);
        messageBodyProperty = messageBodyProperty | (encryption & 0x1C00);
        buff.writeShort(messageBodyProperty);
        buff.writeBcdString(simId);
        buff.writeShort(messageSerialNo);
        if (isPackage) {
            buff.writeShort(messageTotalPacketsCount);
            buff.writeShort(messagePacketNo);
        }
        return buff.array();
    }

    public final void readFromBuf(AutoBuffer buff) {
        messageId = buff.readUnsignedShort();
        messageBodyProperty = buff.readUnsignedShort();
        isPackage = (messageBodyProperty & (1 << 13)) != 0;
        messageLength = messageBodyProperty & 0x03FF;
        encryption = messageBodyProperty & 0x1C00;
        simId = buff.readBcdString(6);
        messageSerialNo = buff.readUnsignedShort();
        if (isPackage) {
            messageTotalPacketsCount = buff.readUnsignedShort();
            messagePacketNo = buff.readUnsignedShort();
        }
    }
}